﻿using AutoMapper;
using B.R.RabbitRoot.Domain.animal_husbandry;
using B.R.RabbitRoot.ErrorCode;
using B.R.RabbitRoot.Infrastructure.Interface;
using B.R.RabbitRoot.Read.API.Applications.Commands.FarmingCommands;
using B.R.RabbitRoot.Read.API.Dtos;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.R.RabbitRoot.Read.API.Applications.CommandHandlers.FarmingCommandHandlers
{
    /// <summary>
    /// 养殖信息命令
    /// </summary>
    public class FarmingQueryCommandHandler : IRequestHandler<FarmingQueryCommand, APIResult<FarmingDTO>>
    {
        private readonly IBaserepository<FarmingDetails> _farmingDetails;
        private readonly IMapper _mapper;
        public FarmingQueryCommandHandler(IBaserepository<FarmingDetails> farmingDetails, IMapper mapper)
        {
            _farmingDetails = farmingDetails;
            _mapper = mapper;
        }

        public async Task<APIResult<FarmingDTO>> Handle(FarmingQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<FarmingDTO> result=new APIResult<FarmingDTO>();
            var lastItem = await _farmingDetails.GetAll().Where(m => m.SourceInfoId == request.SourceInfoId).OrderBy(m=>m.FarmingDetailsId).LastOrDefaultAsync();
            var entity=_mapper.Map<FarmingDTO>(lastItem);
            return await Task.FromResult(result.Success(entity));
        }
    }
}
